package ch.fusun.baron.treasury;

import java.util.HashMap;
import java.util.Map;

import ch.fusun.baron.data.AbstractDataProvider;
import ch.fusun.baron.data.DataUpdate;
import ch.fusun.baron.treasury.api.TreasuryService;

/**
 * The implementation of the treasury service
 */
public class TreasuryServiceImpl extends AbstractDataProvider implements
        TreasuryService {

    private final Map<Object, Integer> moneyMap = new HashMap<Object, Integer>();

    @Override
    public DataUpdate createFullUpdate() {
        synchronized (moneyMap) {
            return new TreasuryDataUpdate(moneyMap);
        }
    }

    @Override
    public void setMoney(Object key, int money) {
        synchronized (moneyMap) {
            moneyMap.put(key, money);
        }
        updateAllListeners(new SetMoneyDataUpdate(key, money));
    }

    @Override
    public int getMoney(Object key) {
        if (key == null) {
            throw new RuntimeException(
                    "Key can't be null in #getMoney of TreasuryService!"); //$NON-NLS-1$
        }
        synchronized (moneyMap) {
            return moneyMap.get(key);
        }
    }

    @Override
    public void removeMoney(Object key, int amount) {
        setMoney(key, getMoney(key) - amount);
    }

    @Override
    public void addMoney(Object key, int amount) {
        setMoney(key, getMoney(key) + amount);
    }

}
